package com.wwdx.controller.base;

import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.wwdx.BaseCommons;
import com.wwdx.model.dto.ResultBean;
import com.wwdx.utils.ConstantHolder;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.SortedMap;

/**
 * 基础控制器
 * @author liguoliang
 * @date 2017-11-13
 */
public abstract class BaseController extends BaseCommons {

    /**
     * 文件上传
     */
    public String upload(MultipartFile multipartFile, String path) {
        String ext = FilenameUtils.getExtension(multipartFile.getOriginalFilename());
        String fileName = super.makeOrderNum() + "." + ext;
        try {
            File file = new File(path + fileName);
            File fileParent = file.getParentFile();
            if(!fileParent.exists()){
                boolean mkdirs = fileParent.mkdirs();
                logger.info("mkdirs:{}",mkdirs);
            }
            boolean newFile = file.createNewFile();
            logger.info("newFile:{}",newFile);
            multipartFile.transferTo(file);
            return fileName;
        } catch (IOException e) {
            logger.error("错误信息：{}",e.getMessage());
            return null;
        }
    }

    /**
     * 验证签名参数是否为空
     */
    protected SortedMap<String, Object> getSortedMap(String token,String sign){
        Preconditions.checkArgument(StringUtils.isNotBlank(token),"token is null");
        Preconditions.checkArgument(StringUtils.isNotBlank(sign),"sign is null");
        SortedMap<String, Object> sortedMap = Maps.newTreeMap();
        sortedMap.put("token", token);
        sortedMap.put("sign", sign);
        return sortedMap;
    }

    /**
     * 验证签名是否正确
     */
	protected ResultBean validSignResult(SortedMap<String, Object> sortedMap){
        String signature = this.createSign(sortedMap);
        String sign = "sign";
        if (!signature.equalsIgnoreCase(sortedMap.get(sign).toString())) {
            String msg = "签名失败";
            return this.renderError(msg);
        }
        return this.renderSuccess();
    }

    /**
     * 验证用户是否登录
     */
    protected ResultBean validSignTokenResult(SortedMap<String, Object> sortedMap){
        ResultBean resultBean = this.validSignResult(sortedMap);
        int status = resultBean.getStatus();
        if (status == 0){
            String unionid = wwdxPersonalService.getByToken(sortedMap.get("token").toString());
            if (unionid == null){
                String msg = "用户账号异常,为了您的账号安全.请重新登录";
                return this.renderError(msg);
            }
            resultBean.setData(unionid);
        }
        return resultBean;
    }

    /**
     * 蜜读接口MD5加密
     * @param sortedMap 签名参数
     * @return 签名
     */
    private String createSign(SortedMap<String, Object> sortedMap) {
        StringBuilder sb = new StringBuilder();
        String sign = "sign",key = "key";
        sortedMap.forEach((k,v)->{
            if (!ObjectUtils.isEmpty(v) && !sign.equals(k) && !key.equals(k)) {
                sb.append(k).append("=").append(v).append("&");
            }
        });
        sb.append("key=wwdxreaderwhat0823");
        return new Md5Hash(sb.toString()).toHex().toUpperCase();
    }

    /**
     * 京东接口MD5加密
     * @param sortedMap 签名参数
     * @return 签名
     */
    protected String jdMd5Sign(SortedMap<String,Object> sortedMap){
        StringBuilder sb = new StringBuilder();
        sortedMap.forEach((k,v)->{
            if (!ObjectUtils.isEmpty(v)) {
                sb.append(k).append(v);
            }
        });
        sb.append(ConstantHolder.Constant.JDENCODE_RULES);
        return new Md5Hash(sb.toString()).toHex();
    }

    /**
     * redis分页
     */
    protected BaseController.Page getRedisPages(int page, int rows){
        if (page > 1){
            page = (page-1) * rows;
            rows = page + rows;
        }else {
            page = 0;
            rows = rows -1;
        }
        return new BaseController.Page(page,rows);
    }

    @Setter
    @Getter
    @AllArgsConstructor
    protected class Page{
        private int page;
        private int rows;
    }

	/**
	 * 渲染失败数据（带消息）
	 * @param msg 需要返回的消息
	 * @return result
	 */
	protected ResultBean renderError(String msg) {
		return new ResultBean(ResultBean.FAIL,msg);
	}

	/**
	 * 渲染成功数据
	 * @return result
	 */
	protected ResultBean renderSuccess() {
		return new ResultBean();
	}

	/**
	 * 渲染成功数据（带数据）
	 * @param obj 需要返回的对象
	 * @return result
	 */
	protected ResultBean renderSuccess(Object obj) {
		return new ResultBean(obj);
	}
}